package com.mxpio.erp.oa.controller;

import com.mxpio.erp.common.oa.entity.OaTravelReimbursement;
import com.mxpio.erp.common.oa.entity.OaTravelReimbursementLine;
import com.mxpio.erp.common.oa.service.OaTravelReimbursementLineService;
import com.mxpio.erp.common.oa.service.OaTravelReimbursementService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.service.DeptService;
import com.mxpioframework.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Tag(name = "OaTravelReimbursementController", description = "差旅报销单")
@RestController
@RequestMapping("/erp/oa/travel/reim/")
public class OaTravelReimbursementController {

    @Autowired
    private OaTravelReimbursementService oaTravelReimbursementService;
    @Autowired
    private OaTravelReimbursementLineService oaTravelReimbursementLineService;
    @Autowired
    private DeptService deptService;
    @GetMapping("list")
    @Operation(summary = "差旅报销单列表", description = "差旅报销单列表（无分页）", method = "GET")
    public Result<List<OaTravelReimbursement>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<OaTravelReimbursement> list = oaTravelReimbursementService.list(OaTravelReimbursement.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "差旅报销单列表", description = "差旅报销单列表（分页）", method = "GET")
    public Result<Page<OaTravelReimbursement>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<OaTravelReimbursement> pageResult = oaTravelReimbursementService.listPage(OaTravelReimbursement.class, page, criteria);
        return Result.OK(pageResult);
    }

    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据ID获取差旅报销单列表", description = "根据ID获取差旅报销单列表", method = "GET")
    public Result<OaTravelReimbursement> getById(@PathVariable(name = "bizNo", required = true) String bizNo) {
        OaTravelReimbursement reimbursement = oaTravelReimbursementService.getById(OaTravelReimbursement.class, bizNo);
        return Result.OK(reimbursement);
    }

    @RequestMapping("save")
    @Operation(summary = "保存差旅报销单列表", description = "保存差旅报销单列表")
    public Result<OaTravelReimbursement> add(@RequestBody OaTravelReimbursement oaTravelReimbursement) {
        Dept levelOneDept = deptService.getLevelOneDept(oaTravelReimbursement.getApplyUserDeptId());
        if (levelOneDept != null) {
            oaTravelReimbursement.setOrgDesc(StringUtils.isNotBlank(levelOneDept.getDeptDesc())?levelOneDept.getDeptDesc():levelOneDept.getDeptName());
        }
        oaTravelReimbursementService.save(oaTravelReimbursement, new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context){
                Object o = context.getEntity();
                if (o instanceof OaTravelReimbursementLine){
                    OaTravelReimbursement info = context.getParent();
                    ((OaTravelReimbursementLine) o).setBizNo(info.getBizNo());
                }
                return  true;
            }
        });
        return Result.OK(oaTravelReimbursement);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑", description = "编辑", method = "PUT")
    public Result<OaTravelReimbursement> edit(@RequestBody OaTravelReimbursement reimbursement) {
        OaTravelReimbursement dbData = oaTravelReimbursementService.getById(OaTravelReimbursement.class,reimbursement.getBizNo());
        if (!StringUtils.equals(dbData.getApplyUserDeptId(),reimbursement.getApplyUserDeptId())){
            Dept levelOneDept = deptService.getLevelOneDept(reimbursement.getApplyUserDeptId());
            if (levelOneDept != null) {
                reimbursement.setOrgDesc(StringUtils.isNotBlank(levelOneDept.getDeptDesc())?levelOneDept.getDeptDesc():levelOneDept.getDeptName());
            }
        }
        oaTravelReimbursementService.update(reimbursement);
        return Result.OK(reimbursement);
    }

    @DeleteMapping("remove/{bizNos}")
    @Operation(summary = "根据bizNo删除单子", description = "删除单子,多个bizNo用英文逗号分隔", method = "DELETE")
    public Result<OaTravelReimbursement> remove(@PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] id = bizNos.split(",");
        for(String key : id){
            oaTravelReimbursementService.delete(OaTravelReimbursement.class, key);
            List<OaTravelReimbursementLine> lines = oaTravelReimbursementLineService.list(OaTravelReimbursementLine.class, Criteria.create().addCriterion("bizNo", Operator.EQ, key));
            for (OaTravelReimbursementLine line : lines){
                oaTravelReimbursementLineService.delete(OaTravelReimbursementLine.class, line.getId());
            }
        }
        return Result.OK();
    }

    /**
     * 编辑审批状态
     * @param reimbursement
     * @return
     */
    @PutMapping("edit/bpmn")
    @Operation(summary = "编辑审批状态", description = "编辑审批状态", method = "PUT")
    public Result<OaTravelReimbursement> editBpmn(@RequestBody OaTravelReimbursement reimbursement) {
        oaTravelReimbursementService.update(reimbursement);
        return Result.OK(reimbursement);
    }

    @RequestMapping("submit/{key}")
    @Operation(summary = "提交申请-工作流",description = "提交申请-工作流")
    public Result<?> change(@PathVariable(name = "key") String key,
                            @RequestParam(value="businessKey", required = false) String businessKey,
                            @RequestBody Map<String, Object> properties) {
        return oaTravelReimbursementService.submit(key, SecurityUtils.getLoginUsername(), businessKey, properties);
    }

    @RequestMapping("submit/Ok")
    @Operation(summary = "提交申请-工作流审核",description = "提交申请-工作流审核")
    public Result<?> submitOK(@RequestBody OaTravelReimbursement reimbursement) {
        return oaTravelReimbursementService.submitOK(reimbursement);
    }
}
